package com.infoauto.opc.gateway.messages.model;

import com.infoauto.opc.gateway.messages.binder.RabbitMQBinder;
import com.infoauto.opc.gateway.messages.enums.ExchangeType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

//RabbitMQ发送者
public class RabbitMQSender {

    private ConnectionFactory connectionFactory;

    private RabbitTemplate rabbitTemplate;

    private String exchangeName;

    private String routingKey;

    private String queueName;

    private ExchangeType exchangeType;

    private RabbitMQBinder binder;

    public RabbitMQSender(ConnectionFactory connectionFactory, String exchangeName, String routingKey) {
        this(connectionFactory, exchangeName, routingKey, null, null);
    }

    public RabbitMQSender(ConnectionFactory connectionFactory, String exchangeName, String routingKey, String queueName,
                          ExchangeType exchangeType) {
        this.connectionFactory = connectionFactory;
        this.exchangeName = exchangeName;
        this.routingKey = routingKey;
        this.queueName = queueName;
        this.exchangeType = exchangeType;
        this.rabbitTemplate = new RabbitTemplate(connectionFactory);
        //mandatory true:如果exchange根据自身类型和消息routingKey找不到queue 则调用basic.return将消息返还给生产者
        //          false:则会将消息丢弃
        this.rabbitTemplate.setMandatory(true);
    }

    public void build() {
        if (StringUtils.isNotBlank(queueName) && exchangeType != null) {
            this.binder = new RabbitMQBinder(connectionFactory);
            this.binder.bind(exchangeName, routingKey, queueName, exchangeType);
        }
    }

 
    public void send(String routingKey, Object message) {
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
    }

    public void send(Object message) {
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);
    }
}
